﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization.Formatters.Binary;
using SSAT.Utils;

namespace SSAT.ConnectionStringsManagement
{
    internal sealed class IsolatedStorageStringsSaver : IConnectionStringsSaver
    {
        public const string ConnectionsFile = "Conns.dat";

        public void Save(string dataSource, string connectionString)
        {
            IDictionary<string, string> conns = Load();
            conns[dataSource] = connectionString;

            using (IsolatedStorageFileStream file = GetConnectionsFile())
            {
                BinaryFormatter serializer = new BinaryFormatter();
                serializer.Serialize(file, conns);
            }
        }

        public IDictionary<string, string> Load()
        {
            IDictionary<string, string> result = null;
            try
            {
                using (IsolatedStorageFileStream file = GetConnectionsFile())
                {
                    var serializer = new BinaryFormatter();
                    result = serializer.Deserialize(file) as IDictionary<string, string>;
                }
            }
            catch (Exception)
            {
                // If we can't read file with connection strings then try to silently delete it.
                try
                {
                    using (IsolatedStorageFile isolatedStorageFile = GetIsolatedStorageFile())
                    {
                        isolatedStorageFile.DeleteFile(ConnectionsFile);
                    }
                }
                catch (Exception ex)
                {
                    Logging.Handle(ex);
                }
            }
            return result ?? new Dictionary<string, string>();
        }

        private static IsolatedStorageFileStream GetConnectionsFile()
        {
            return new IsolatedStorageFileStream(ConnectionsFile, FileMode.OpenOrCreate, GetIsolatedStorageFile());
        }

        private static IsolatedStorageFile GetIsolatedStorageFile()
        {
            return IsolatedStorageFile.GetUserStoreForAssembly();
        }
    }
}
